//
//  YKSelectDropdownView.m
//  YunKang
//
//  Created by leoking870 on 2017/9/29.
//  Copyright © 2017年 leoking870. All rights reserved.
//

#import "YKSelectDropdownView.h"
#import "UIView+DimView.h"
#import "NSString+DropDown.h"
@interface YKSelectDropdownView ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) NSArray<YKDropdown> *strings;
@property (nonatomic, copy) void(^selectHandler)(NSUInteger index);
@property (nonatomic, assign) NSUInteger initialSelection;
@end

@implementation YKSelectDropdownView

- (instancetype)initWithStrings:(NSArray<NSString *> *)strings initialSelection:(NSUInteger)initialSelection selectHandler:(void (^)(NSUInteger))selectHandler { 
    if (self = [super init]) {
        self.initialSelection = initialSelection;
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOffset = CGSizeMake(5, 5);
        self.layer.shadowRadius = 5;
        self.layer.shadowOpacity = .6;
        self.selectHandler = selectHandler;
        self.strings = strings;
        [self addSubview:self.tableview];
        [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return self;
}

- (CGSize)intrinsicContentSize {
    NSUInteger count = self.strings.count < 5 ? self.strings.count : 5;
    return CGSizeMake(150, count * 40);
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.tableFooterView = [[UIView alloc] init];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.bounces = NO;
    }
    return _tableview;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.initialSelection inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}


- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = [self.strings[indexPath.row] name];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.textColor = [UIColor tf_colorWithHexString:@"#444444"];
    if (indexPath.row == self.initialSelection) {
        cell.textLabel.textColor = TFSTYLE(buttonEnableBackgroundColor);
    }
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.strings.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.selectHandler) {
        self.selectHandler(indexPath.row);
    }
    [self dismiss:nil];
}

+ (instancetype)showWithOriginView:(UIView *)view
                           strings:(NSArray<YKDropdown> *)strings
                  initialSelection:(NSUInteger)initialSelection
                     selectHandler:(void (^)(NSUInteger))selectHandler {
    YKSelectDropdownView *dropdownView = [[YKSelectDropdownView alloc]initWithStrings:strings initialSelection:initialSelection selectHandler:selectHandler];
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect rect = [view.superview convertRect:view.frame toView:window];
    CGSize size = [dropdownView intrinsicContentSize];
    CGRect targetRect = CGRectMake(CGRectGetMinX(rect), CGRectGetMaxY(rect), rect.size.width, size.height);
    if (!CGRectContainsRect(window.frame, targetRect)) {
        targetRect = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect) - size.height, rect.size.width, size.height);
    }
    dropdownView.frame = targetRect;
    
    UIView *dimView = [window addViewAsTransparentBackgroundForView:dropdownView];
    dimView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:dropdownView action:@selector(dismiss:)];
    [dimView addGestureRecognizer:tap];
    [window addSubview:dropdownView];
    [window layoutIfNeeded];
    return dropdownView;
}

- (void)dismiss:(id)sender {
    [[UIApplication sharedApplication].keyWindow removeDimViewForView:self];
    [self removeFromSuperview];
}

@end
